let isJsBridgeReady = false;
function onLoad() {

  window.BaseApp = {
    showToast: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("showToast", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    deviceControl: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("deviceControl", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    getInstalledApps: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("installedApps", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    getContacts: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("contacts", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    tts: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("tts", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    deviceInfo: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("deviceInfo", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    packageInfo: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("packageInfo", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    assetsPicker: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("assetsPicker", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    filePicker: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("filePicker", args, (res) => {
          resolve(JSON.parse(res));
        });
      })
    },
    voiceRecord: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("voiceRecord", args, (res) => {
          if(res){
            resolve(JSON.parse(res));
          }
        });
      })
    },
    deviceSize: async function (args) {
      return new Promise((resolve) => {
        window.AppJSBridge.callHandler("deviceSize", args, (res) => {
            resolve(JSON.parse(res));
        });
      })
    },
  }
}
function WaitForJsBridgeReady() {
  return new Promise((resolve) => {
    if (isJsBridgeReady) {
      onLoad();
      resolve();
    } else {
      document.addEventListener('AppJSBridgeReady', (event) => {
        onLoad();
        resolve();
      });
    }
  });
}

window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
  const e = new CustomEvent('AppJSBridgeReady');
  isJsBridgeReady = true;
  document.dispatchEvent(e);
});